from sqlalchemy import Column, String, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockUpLimit(Base):
    __tablename__ = 'stock_up_limit'
    id = Column(Integer, primary_key=True, autoincrement=True)
    qdate = Column(String(10), comment='日期（yyyy-MM-dd）')
    dm = Column(String(6), comment='代码')
    mc = Column(String(50), comment='名称')
    p = Column(String(20), comment='价格（元）')
    zf = Column(String(10), comment='涨幅（%）')
    cje = Column(String(20), comment='成交额（元）')
    lt = Column(String(20), comment='流通市值（元）')
    zsz = Column(String(20), comment='总市值（元）')
    hs = Column(String(10), comment='换手率（%）')
    lbc = Column(Integer, comment='连板数')
    fbt = Column(String(20), comment='首次封板时间（HH:mm:ss）')
    lbt = Column(String(20), comment='最后封板时间（HH:mm:ss）')
    zj = Column(String(20), comment='封板资金（元）')
    zbc = Column(Integer, comment='炸板次数')
    tj = Column(String(20), comment='涨停统计（x天/y板）')

    def __init__(self, qdate, dm, mc, p, zf, cje, lt, zsz, hs, lbc, fbt, lbt, zj, zbc, tj):
        self.qdate = qdate
        self.dm = dm
        self.mc = mc
        self.p = p
        self.zf = zf
        self.cje = cje
        self.lt = lt
        self.zsz = zsz
        self.hs = hs
        self.lbc = lbc
        self.fbt = fbt
        self.lbt = lbt
        self.zj = zj
        self.zbc = zbc
        self.tj = tj

    @staticmethod
    def not_exist_insert(qdate, data_list):
        session = sessionmaker(bind=engine)()
        existing_stock_up_limit = session.query(StockUpLimit).filter_by(qdate=qdate).first()
        if existing_stock_up_limit:
            return
        for data in data_list:
            session.add(
                StockUpLimit(qdate=qdate, dm=data['dm'], mc=data['mc'], p=data['p'], zf=data['zf'], cje=data['cje'],
                             lt=data['lt'], zsz=data['zsz'], hs=data['hs'], lbc=data['lbc'], fbt=data['fbt'],
                             lbt=data['lbt'], zj=data['zj'], zbc=data['zbc'], tj=data['tj']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
